<?php


namespace support\command;

use Symfony\Component\Console\Command\Command as C;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Workerman\Worker as W;

/**
 * worker相关命令
 */
class Worker extends C
{
    protected static $defaultName = 'worker';

    protected $io = null;

    protected function configure()
    {
        $this->addArgument('action', InputArgument::REQUIRED, '命令:start|stop|restart|reload|status|connections')
            ->addArgument('mode', InputArgument::OPTIONAL, 'mode:d|g')
            ->setDescription('启动注册的workerman服务')
            ->setHelp('启动所有的workerman服务');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->io = new SymfonyStyle($input, $output);
        global $argv;
        $action = $input->getArgument('action');
        $mode = $input->getArgument('mode');
        $argv[1] = self::$defaultName;
        $argv[2] = $action;
        $argv[3] = $mode ? '-' . $mode : '';
        $this->start();
        W::runAll();
        return self::SUCCESS;
    }

    private function start()
    {
        $workers = config('worker');
        foreach ($workers as $className) {
            /**
             * @var \support\command\workerman\Worker $className
             */
            $class = new $className;
            if (!$class instanceof \support\command\workerman\Worker || !method_exists($class, 'register') ) {
                if (!$this->io->confirm('class ' . $className . ' not implements . ' . \support\command\workerman\Worker::class . ' and not has method `register`, Are you sure to continue?')) {
                    continue;
                }
                $this->io->error("停止启动!");
            }
            if (method_exists($class, 'register')) {
                $class->register();
            }
        }
        $this->io->writeln("");
    }
}
